package com.stars.sun.mvc;

import com.stars.sun.reflect.MyReflect;
import com.stars.sun.service.BaseService;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by 340082 on 2018/4/28.
 *@author jiyx
 * 反射调用方法的核心类
 */
public class ActionHandler {

    /**
     * 反射调用方法
     * @param req
     * @param resp
     */
    public void handler(HttpServletRequest req, HttpServletResponse resp){
        String servletPath = req.getServletPath();
        MappingNode<ActionInfo> rootMapping = MyReflect.rootMapping;
        ActionInfo actionInfo = rootMapping.get(servletPath);
        Class moduleType =  actionInfo.getModuleType();
        Method moduleMethod = actionInfo.getModuleMethod();
        Class<?>[] parameterTypes = moduleMethod.getParameterTypes();
        for (int i = 0 ; i< parameterTypes.length ; i++){
            System.out.println(parameterTypes[i]);
        }
        try {
            Object o = moduleType.newInstance();
            this.getProperties(req);
            moduleMethod.invoke(o,null);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(actionInfo);
    }

    /**
     * TODO 获取参数用
     * 没有写
     * @param req
     */
    private void getProperties(HttpServletRequest req) {
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()){
            System.out.println(req.getHeader(headerNames.nextElement()));
        }

        System.out.println(req.getHeader("Content-Type"));
//        String accept = (String) headerNames;
//        System.out.println(accept);
        Map<String, String[]> parameterMap = req.getParameterMap();
        try {
            BufferedReader reader = req.getReader();
            String line = null;
            while ((line = reader.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(parameterMap);
        String servletPath = req.getServletPath();
        String[] split = servletPath.split("/");
        for (String s:split) {
            System.out.println(s);
        }
    }
}
